# -*- coding: utf-8 -*-

'''eof
name:申请人12个月内（贷款、贷记卡记准贷记卡）累计逾期次数
code:IC24_Ind1yearAccmOvduCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import datetime
import pandas as pd

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False



#获取单个账户的累计逾期次数
def getOneYearsOvduCount(statusList, min, max):
    if statusList in null_type_list:
        return None
    # 使用当前时间为阈值
    endMonthStr = datetime.datetime.now().strftime("%Y-%m-%d")
    endMonth = float(endMonthStr[:4]) * 12 + float(endMonthStr[5:7])
    month12Ago = endMonth - 12
    result = 0
    flag = False
    for i in statusList:
        try:
            PD01ER03 = i.get('PD01ER03')
            PD01ED01 = i.get('PD01ED01')
            PD01ER03 = float(PD01ER03[:4]) *12 + float(PD01ER03[5:7]) if len(PD01ER03) >= 6 else None
            if PD01ER03 not in null_type_list and PD01ED01 not in null_type_list:
                flag = True
            if month12Ago < PD01ER03 <= endMonth and intCheck(PD01ED01) and min <= int(PD01ED01) <= max:
                result += 1
        except:
            continue
    if flag:
        return result
    else:
        return None

#贷款单账户12个月内累计逾期次数最大值
def IC24_Ind1yearContinuousOvduMonth_1():
    data = IC_DSJ_2D.get('data')
    # 借贷账户信息,出现次数[1..1],下级字段出现次数[0..1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元,出现次数[1..*],下级字段出现次数[1..1]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段,出现次数[1..1],下级字段出现次数[1..1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 in ["D1","R1","R4"]:
                                # 最近5年内的历史表现信息段,出现次数[0..1],下级字段出现次数[1..60]
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}]:
                                    factor.append(None)
                                elif PD01E == 0:
                                    pass
                                else:
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    if PD01EH in null_type_list:
                                        factor.append(None)
                                    else:
                                        tem = getOneYearsOvduCount(PD01EH,min = 1,max = 7)
                                        if tem == None:
                                            factor.append(None)
                                        else:
                                            factor.append(tem)

                            else:
                                pass
                        else:
                            factor.append(None)
                except:
                    factor.append(None)

    if None in factor:
        factor = [x for x in factor if x is not None]
        if len(factor) == 0:
            return u'缺失值'
        else:
            return sum(factor) 
    elif len(factor) == 0:
        return 0
    else:
        return sum(factor)
#贷记卡单账户12个月内累计逾期次数最大值  
def IC24_Ind1yearContinuousOvduMonth_2():
    data = IC_DSJ_2D.get('data')
    # 借贷账户信息,出现次数[1..1],下级字段出现次数[0..1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元,出现次数[1..*],下级字段出现次数[1..1]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段,出现次数[1..1],下级字段出现次数[1..1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 in ["R2"]:
                                # 最近5年内的历史表现信息段,出现次数[0..1],下级字段出现次数[1..60]
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}]:
                                    factor.append(None)
                                elif PD01E == 0:
                                    pass
                                else:
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    if PD01EH in null_type_list:
                                        factor.append(None)
                                    else:
                                        tem = getOneYearsOvduCount(PD01EH,min = 1,max = 7)
                                        if tem == None:
                                            factor.append(None)
                                        else:
                                            factor.append(tem)

                            else:
                                pass
                        else:
                            factor.append(None)
                except:
                    factor.append(None)

    if None in factor:
        factor = [x for x in factor if x is not None]
        if len(factor) == 0:
            return u'缺失值'
        else:
            return sum(factor) 
    elif len(factor) == 0:
        return 0
    else:
        return sum(factor)

#准贷记卡单账户12个月内累计逾期次数最大值 
def IC24_Ind1yearContinuousOvduMonth_3():
    data = IC_DSJ_2D.get('data')
    # 借贷账户信息,出现次数[1..1],下级字段出现次数[0..1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元,出现次数[1..*],下级字段出现次数[1..1]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段,出现次数[1..1],下级字段出现次数[1..1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 in ["R3"]:
                                # 最近5年内的历史表现信息段,出现次数[0..1],下级字段出现次数[1..60]
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}]:
                                    factor.append(None)
                                elif PD01E == 0:
                                    pass
                                else:
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    if PD01EH in null_type_list:
                                        factor.append(None)
                                    else:
                                        tem = getOneYearsOvduCount(PD01EH,min = 3,max = 7)
                                        if tem == None:
                                            factor.append(None)
                                        else:
                                            factor.append(tem)

                            else:
                                pass
                        else:
                            factor.append(None)
                except:
                    factor.append(None)

    if None in factor:
        factor = [x for x in factor if x is not None]
        if len(factor) == 0:
            return u'缺失值'
        else:
            return sum(factor) 
    elif len(factor) == 0:
        return 0
    else:
        return sum(factor)
    
    
    
def summary():
    x_result = IC24_Ind1yearContinuousOvduMonth_1()
    y_result = IC24_Ind1yearContinuousOvduMonth_2()
    z_result = IC24_Ind1yearContinuousOvduMonth_3()
    # x = u"贷款单账户12个月内累计逾期次数最大值"
    # y = u"贷记卡单账户12个月内累计逾期次数最大值"
    # z = u"准贷记卡单账户12个月内累计逾期次数最大值"
    if x_result == y_result == z_result == u'缺失值':
        return u'缺失值'
    else:
        result_list = [x_result,y_result,z_result]
        result_list = [x for x in result_list if x != u'缺失值']
        return sum(result_list)

result = summary()
